<?
/*
  This agi is a good example for showing how to use API manager inside an AGI.
  It works checking if an extension is on the phone or not.
  The result is stored in a channel variable ONTHEPHONE.
*/

/*********************** INCLUDES *********************************************/
  $includePath=realpath(dirname(__FILE__)."/../");
  require_once ($includePath.'/config/cfg.php');
  //require($includePath.'/constants.php');
  require_once ($includePath.'/lib/phpagi/phpagi.php');
  require_once ($includePath.'/lib/phpagi/phpagi-asmanager.php');
  //require($includePath.'/agi/agifunction.php');
/*********************** INITIALIZATION ***************************************/

  $agi = new AGI();
  // Get AGI parameters 
  parse_str($_SERVER["argv"][1], $var_GET);
  $channel=$var_GET["channel"];
  
/*********************** PAGE LOGIC ********************************************/
  
  agiError("  Executing the SHOW CHANNELS command... ($channel)");
  if(!isset($_SERVER['argv'][1])) {
    agiError("ERROR:\tThe AGI isbusy.php require at least 1 parameter, the channel to analize\n\n");
    agiError("Usage:\tisbusy.php|sip/202\n\n");
    exit;
  }
    
  $asm = new AGI_AsteriskManager();
  if($asm->connect($API_host,$API_user,$API_pass)) {
    $peer = $asm->command("show channels");
    if(!strpos($peer['data'], ':'))
      echo $peer['data'];
    else {
      $data = array();
      foreach(explode("\n", $peer['data']) as $line){
        $a = strpos($line, '-');
        if($a !==false ) $data[trim(substr($line, 0, $a))] = trim(substr($line, $a + 1));
      }      
      if (array_key_exists($channel,$data)) {
        $agi->set_variable("ONTHEPHONE","TRUE");
        agiError("ONTHEPHONE: TRUE");
      } else { 
        $agi->set_variable("ONTHEPHONE","FALSE");
        agiError("ONTHEPHONE: FALSE");
      }
    }
    $asm->disconnect();
  }

?>
